<?php
// +-------------+--------------+------+-----+---------+----------------+
// | Field       | Type         | Null | Key | Default | Extra          |
// +-------------+--------------+------+-----+---------+----------------+
// | id          | int(11)      | NO   | PRI | NULL    | auto_increment |
// | save_path   | varchar(200) | YES  |     |         |                |
// | ext         | varchar(10)  | YES  |     |         |                |
// | mine_type   | varchar(30)  | YES  |     |         |                |
// | size        | int(11)      | YES  |     | 0       |                |
// | sha1        | varchar(40)  | YES  |     |         |                |
// | md5         | varchar(40)  | YES  |     |         |                |
// | user_id     | int(11)      | YES  |     | 0       |                |
// | create_time | int(11)      | YES  |     | 0       |                |
// | update_time | int(11)      | YES  |     | 0       |                |
// +-------------+--------------+------+-----+---------+----------------+
namespace app\common\model;
use think\Loader;
use app\common\model\Base;
use think\Request;
class Upload extends Base{
  protected $auto = ["user_id"];

  public function findWithUser($id){
    $user_id = login_user_id();
    $upload = $this->where("id", $id)->where("user_id", $user_id)->find();
    return $upload;
  }

  public function ueditorList($start = 0, $size = 20){
    $user_id = login_user_id();
    $total_count = $this->count();

    $start = intval($start);
    if($start < 0){
      $start = 0;
    }

    $size = intval($size);
    if($size < 0 || $size > 20){
      $size = 20;
    }

    $select_fields = [
      "save_path AS url",
      "create_time AS mtime",
    ];
    $list = $this->field($select_fields)->where("user_id", $user_id)->order("id DESC")->limit("{$start}, {$size}")->select();

    $res = [
      "state" => "SUCCESS",
      "list" => $list,
      "start" => $start,
      "total" => $total_count,
    ];
    return $res;
  }

  /**
   * 保存上传文件
   * @Author zhanghong
   * @Date   2017-01-03
   * @param  [type]     $file     [description]
   * @param  string     $save_dir [description]
   * @return [type]               [description]
   */
  public function saveFile($file, $upload_type = "", $save_dir = "upload"){
    $save_root = ROOT_PATH.'public';
    $local_dir = DS . $save_dir;
    $info = $file->move($save_root.$local_dir);

    $data = [];
    $data["ext"] = $info->getExtension();
    $save_name = $info->getSaveName();
    $data["save_path"] = $local_dir.DS.$save_name;
    $data["file_name"] = $info->getFilename();
    $data["sha1"] = $info->hash("sha1");
    $data["md5"] = $info->hash("md5");
    $data["mine_type"] = $info->getMime();
    $data["size"] = $info->getSize();
    $data["upload_type"] = $upload_type;
    $this->data($data)->allowField(true)->save();
    $data["id"] = $this->id;
    return $data;
  }
}